# -*- coding: utf-8 -*-
"""
乒乓球培训管理系统 - 球台视图

球台管理相关的路由处理
包括球台CRUD操作、状态管理、使用统计等功能
"""

from flask import Blueprint, render_template, request, redirect, url_for, flash, jsonify
from flask_login import login_required, current_user
from app.forms.table_forms import (
    TableCreateForm, TableEditForm, TableSearchForm,
    TableDeleteForm, TableBatchForm, TableStatusForm
)
from app.controllers.table_controller import TableController
from app.utils.decorators import admin_required, super_admin_required

# 创建球台蓝图
tables_bp = Blueprint('tables', __name__)


@tables_bp.route('/')
@tables_bp.route('/list')
@admin_required
def list():
    """
    球台列表页

    支持搜索、筛选、分页功能
    """
    form = TableSearchForm()

    # 获取搜索参数
    page = request.args.get('page', 1, type=int)
    keyword = request.args.get('keyword', '')
    campus_id = request.args.get('campus_id', '', type=str)
    status = request.args.get('status', '')
    sort_by = request.args.get('sort_by', 'created_at_desc')

    # 转换campus_id
    campus_id = int(campus_id) if campus_id and campus_id.isdigit() else None

    # 设置表单默认值
    if request.method == 'GET':
        form.keyword.data = keyword
        form.campus_id.data = campus_id
        form.status.data = status
        form.sort_by.data = sort_by

    # 获取球台列表
    pagination, total = TableController.get_table_list(
        page=page,
        per_page=12,
        keyword=keyword,
        campus_id=campus_id,
        status=status,
        sort_by=sort_by
    )

    # 获取汇总统计
    summary = TableController.get_campus_table_summary(campus_id)

    return render_template(
        'tables/list.html',
        form=form,
        pagination=pagination,
        tables=pagination.items,
        total=total,
        summary=summary
    )


@tables_bp.route('/<int:id>')
@admin_required
def detail(id):
    """
    球台详情页

    显示球台完整信息和使用统计
    """
    table = TableController.get_table_by_id(id)
    if not table:
        flash('球台不存在或无权限访问', 'error')
        return redirect(url_for('tables.list'))

    # 获取球台使用统计
    statistics = TableController.get_table_statistics(id)

    # 状态快速切换表单
    status_form = TableStatusForm()
    status_form.table_id.data = id
    status_form.status.data = table.status

    return render_template(
        'tables/detail.html',
        table=table,
        statistics=statistics,
        status_form=status_form
    )


@tables_bp.route('/create', methods=['GET', 'POST'])
@admin_required
def create():
    """
    创建球台页

    校区管理员可以在自己的校区创建球台
    超级管理员可以在任意校区创建球台
    """
    form = TableCreateForm()

    if request.method == 'POST':
        if form.validate_on_submit():
            # 获取表单数据
            form_data = {
                'name': form.name.data,
                'campus_id': form.campus_id.data,
                'status': form.status.data,
                'is_active': form.is_active.data
            }

            # 创建球台
            success, result = TableController.create_table(form_data)

            if success:
                flash(f'球台"{result.name}"创建成功！', 'success')
                return redirect(url_for('tables.detail', id=result.id))
            else:
                flash(f'创建失败：{result}', 'error')
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    flash(f'{form[field].label.text}: {error}', 'error')

    return render_template('tables/create.html', form=form)


@tables_bp.route('/<int:id>/edit', methods=['GET', 'POST'])
@admin_required
def edit(id):
    """
    编辑球台页

    校区管理员可以编辑自己校区的球台
    超级管理员可以编辑任意球台
    """
    table = TableController.get_table_by_id(id)
    if not table:
        flash('球台不存在或无权限访问', 'error')
        return redirect(url_for('tables.list'))

    form = TableEditForm(table=table)

    if request.method == 'GET':
        # 填充表单数据
        form.name.data = table.name
        form.campus_id.data = table.campus_id
        form.status.data = table.status
        form.is_active.data = (table.status != 'disabled')

    if request.method == 'POST':
        if form.validate_on_submit():
            # 获取表单数据
            form_data = {
                'name': form.name.data,
                'campus_id': form.campus_id.data,
                'status': form.status.data,
                'is_active': form.is_active.data
            }

            # 更新球台
            success, error_msg = TableController.update_table(table, form_data)

            if success:
                flash(f'球台"{table.name}"更新成功！', 'success')
                return redirect(url_for('tables.detail', id=table.id))
            else:
                flash(f'更新失败：{error_msg}', 'error')
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    flash(f'{form[field].label.text}: {error}', 'error')

    return render_template('tables/edit.html', form=form, table=table)


@tables_bp.route('/<int:id>/delete', methods=['GET', 'POST'])
@admin_required
def delete(id):
    """
    删除球台页

    需要确认删除操作
    """
    table = TableController.get_table_by_id(id)
    if not table:
        flash('球台不存在或无权限访问', 'error')
        return redirect(url_for('tables.list'))

    form = TableDeleteForm()
    form.table_id.data = id

    if request.method == 'POST':
        if form.validate_on_submit():
            success, error_msg = TableController.delete_table(id)

            if success:
                flash(f'球台"{table.name}"已删除', 'success')
                return redirect(url_for('tables.list'))
            else:
                flash(f'删除失败：{error_msg}', 'error')
        else:
            # 显示表单验证错误
            for field, errors in form.errors.items():
                for error in errors:
                    flash(error, 'error')

    return render_template('tables/delete_confirm.html', form=form, table=table)


@tables_bp.route('/batch', methods=['POST'])
@admin_required
def batch_operation():
    """
    批量操作球台

    支持批量状态更新和删除
    """
    form = TableBatchForm()

    if form.validate_on_submit():
        try:
            table_ids = [int(id.strip()) for id in form.table_ids.data.split(',') if id.strip()]
            action = form.action.data

            success_count, fail_count, errors = TableController.batch_operation(
                table_ids, action
            )

            # 构建结果消息
            if success_count > 0:
                action_text = {
                    'available': '设为可用',
                    'maintenance': '设为维护',
                    'disabled': '设为禁用',
                    'delete': '删除'
                }.get(action, '操作')
                flash(f'成功{action_text}{success_count}个球台', 'success')

            if fail_count > 0:
                flash(f'{fail_count}个球台操作失败', 'warning')
                for error in errors[:5]:  # 只显示前5个错误
                    flash(error, 'error')

        except Exception as e:
            flash(f'批量操作失败：{str(e)}', 'error')
    else:
        # 显示表单验证错误
        for field, errors in form.errors.items():
            for error in errors:
                flash(error, 'error')

    return redirect(url_for('tables.list'))


@tables_bp.route('/<int:id>/status', methods=['POST'])
@admin_required
def update_status(id):
    """
    更新球台状态

    用于快速状态切换
    """
    form = TableStatusForm()

    if form.validate_on_submit():
        success, error_msg = TableController.update_table_status(id, form.status.data)

        if success:
            flash('状态更新成功', 'success')
        else:
            flash(f'状态更新失败：{error_msg}', 'error')
    else:
        for field, errors in form.errors.items():
            for error in errors:
                flash(error, 'error')

    return redirect(url_for('tables.detail', id=id))


@tables_bp.route('/api/search')
@admin_required
def api_search():
    """
    球台搜索API

    用于AJAX请求获取球台列表
    """
    keyword = request.args.get('keyword', '')
    campus_id = request.args.get('campus_id', '', type=str)
    campus_id = int(campus_id) if campus_id and campus_id.isdigit() else None
    page = request.args.get('page', 1, type=int)
    per_page = request.args.get('per_page', 12, type=int)

    try:
        pagination, total = TableController.get_table_list(
            page=page,
            per_page=per_page,
            keyword=keyword,
            campus_id=campus_id
        )

        tables_data = []
        for table in pagination.items:
            tables_data.append({
                'id': table.id,
                'name': table.name,
                'campus_name': table.campus.name if table.campus else '',
                'status': table.status,
                'created_at': table.created_at.strftime('%Y-%m-%d') if table.created_at else ''
            })

        return jsonify({
            'success': True,
            'data': tables_data,
            'pagination': {
                'page': pagination.page,
                'pages': pagination.pages,
                'per_page': pagination.per_page,
                'total': pagination.total,
                'has_prev': pagination.has_prev,
                'has_next': pagination.has_next
            }
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@tables_bp.route('/api/<int:id>/statistics')
@admin_required
def api_statistics(id):
    """
    球台统计API

    获取球台的使用统计信息
    """
    table = TableController.get_table_by_id(id)
    if not table:
        return jsonify({'success': False, 'error': '球台不存在或无权限访问'}), 404

    try:
        statistics = TableController.get_table_statistics(id)
        return jsonify({
            'success': True,
            'data': statistics
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500


@tables_bp.route('/api/summary')
@admin_required
def api_summary():
    """
    球台汇总统计API

    获取校区的球台汇总信息
    """
    campus_id = request.args.get('campus_id', '', type=str)
    campus_id = int(campus_id) if campus_id and campus_id.isdigit() else None

    try:
        summary = TableController.get_campus_table_summary(campus_id)
        return jsonify({
            'success': True,
            'data': summary
        })

    except Exception as e:
        return jsonify({
            'success': False,
            'error': str(e)
        }), 500